package com.tdcy.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tdcy.framework.exception.BaseException;
import com.tdcy.framework.util.ContextUtils;
import com.tdcy.framework.util.CryptoHUtils;
import com.tdcy.framework.util.RequestUtils;
import com.tdcy.sys.dao.IAccessDAO;
import com.tdcy.sys.dao.eo.AccessEO;

/**
 * rest拦截器
 * @author chenyong
 */
public class RestHandlerInterceptor extends HandlerInterceptorAdapter {
	private static Logger log = LoggerFactory.getLogger(RestHandlerInterceptor.class);
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String uri = request.getServletPath();

		if (!RequestUtils.isRestRequest(request)) {
			return true;
		}
		
		log.info("REST参数：" + RequestUtils.getAllParameters(request));
		authRest(request,response); //验证rest
		return true;
	}
	


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	

	public void authRest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String sign = request.getParameter("sign");
		String appid = request.getParameter("appid");
		try {
			appid = CryptoHUtils.base64Decoder(appid);
		} catch (Exception e) {
			throw new BaseException("密码加密出错");
		}
		String timestamp = request.getParameter("timestamp");

		IAccessDAO accessModeDao = ContextUtils.getApplicationContext().getBean(IAccessDAO.class);
		AccessEO aeo = accessModeDao.findByAppId(appid);
		if (aeo == null) {
			throw new BaseException("找不到rest用户信息");
		}

		String usign = aeo.getVerfiyName() + aeo.getVerfiyPassword() + timestamp;
		String signstr = CryptoHUtils.md5(usign);
		if (!signstr.equalsIgnoreCase(sign)) {
			throw new BaseException("rest签名串不正确");
		}

	}
}
